<script lang="ts" setup>
import type { FormInstance } from '@arco-design/web-vue'
import { Message, Notification } from '@arco-design/web-vue'
import ConflictTip from './components/ConflictTip.vue'
import { useDictLabel, useForm } from '@/hooks'
import { ArrangeTemplateApi, ClassInfoApi, ClassTypeApi, ClassroomApi, EmployeeApi, TimeTemplateApi } from '@/apis'
import { calculateGradeLimitLegacy } from '@/utils/edu'
import type { TableInstanceColumns } from '@/components/ProTable/type'

defineOptions({
  name: 'ClassBatchCreate',
})

// 批量创建表单
const form = ref<any>({
  classYear: new Date().getFullYear(),
  term: undefined,
  grade: undefined,
  lessonChangeLimit: 3,
  totalPrice: undefined,
  unitPrice: undefined,
  renewalStartTime: undefined,
  renewalEndTime: undefined,
  enrollStartTime: undefined,
  planStudentCount: undefined,
  lessonHourFactor: 3.0,
  salePerformanceFactor: 1.0,
  saleStatus: 0,
})
const classList = ref<any[]>([])
const columns: TableInstanceColumns[] = [
  {
    title: '序号',
    width: 66,
    align: 'center',
    fixed: 'left',
    render: ({ rowIndex }) => h('span', {}, rowIndex + 1),
  },
  { title: '班级名称', dataIndex: 'name', slotName: 'name', fixed: 'left', width: 420 },
  { title: '主讲老师', dataIndex: 'leadTeacherId', slotName: 'leadTeacherId', width: 180 },
  { title: '辅导老师', dataIndex: 'assistTeacherId', slotName: 'assistTeacherId', width: 180 },
  { title: '校区教室', dataIndex: 'classroomId', slotName: 'classroomId', width: 180 },

  { title: '上课期段', dataIndex: 'arrangeTemplateId', slotName: 'arrangeTemplateId', width: 210 },
  { title: '上课时间段', dataIndex: 'timeTemplateId', slotName: 'timeTemplateId', width: 210 },
  { title: '班型', dataIndex: 'classTypeId', slotName: 'classTypeId', width: 180 },
  { title: '入学年份限制', dataIndex: 'admissionYearLimit', slotName: 'admissionYearLimit', width: 180 },
  { title: '权限限制', dataIndex: 'enrollPermission', slotName: 'enrollPermission', width: 250 },
  { title: '状态', slotName: 'status', align: 'center', fixed: 'right', width: 150 },
]

// 班级筛选
const formSize = 'small'
const { form: classQuery } = useForm<ClassInfoApi.ClassQuery>({
  classYear: new Date().getFullYear(),
  term: 'SPRING',
  grade: 'grade1',
  subject: 'math-xx',
  classCategory: 1,
})
const classLoading = ref(false)
const searchClass = async () => {
  try {
    classLoading.value = true
    const prevClassList = await ClassInfoApi.getPrevClassList(classQuery)
    form.value.classYear = classQuery.classYear
    form.value.subject = classQuery.subject
    form.value.term = classQuery.term
    form.value.grade = classQuery.grade
    form.value.classCategory = classQuery.classCategory

    classList.value = []
    prevClassList.forEach((item) => {
      classList.value.push({
        prevClassId: item.id,
        prevClassName: item.name,
        prevClassLeadTeacherName: item.leadTeacherName,
        name: undefined,
        admissionYearLimit: undefined,
        classTypeId: item.classTypeId,
        classLevelLimit: undefined,
        campusId: item.campusId,
        classroomId: item.classroomId,
        leadTeacherId: item.leadTeacherId,
        assistTeacherId: item.assistTeacherId,
        arrangeTemplateId: undefined,
        timeTemplateId: undefined,
        image: undefined,
        description: undefined,
        createStatus: undefined,
        needCreate: true,
      })
    })
  } finally {
    classLoading.value = false
  }
}

const router = useRouter()

// 校区教室
const classroomList = ref<any[]>([])
const getClassroomList = async () => {
  classroomList.value = await ClassroomApi.getList({})
}

// 主讲老师
const leadTeacherList = ref<any[]>([])
const getLeadTeacherList = async () => {
  leadTeacherList.value = await EmployeeApi.getList({
    status: 1,
    type: 'LEAD_TEACHER',
  })
}

// 辅导老师
const assistTeacherList = ref<any[]>([])
const getAssistTeacherList = async () => {
  assistTeacherList.value = await EmployeeApi.getList({
    status: 1,
    type: 'ASSIST_TEACHER',
  })
}

// 班型
const classTypeList = ref<any[]>([])
const getClassTypeList = async () => {
  classTypeList.value = await ClassTypeApi.getList({})
}
const onClassTypeSelect = (event, index) => {
  console.log('onClassTypeSelect: ', event, index)
  classList.value[index].classLevelLimit = event.level
  classList.value[index].classTypeName = event.name
}

// 期段
const arrangeTemplateList = ref<any[]>([])
const getArrangeTemplateList = async () => {
  arrangeTemplateList.value = await ArrangeTemplateApi.getArrangeTemplateList({
    classYear: form.value.classYear,
    term: form.value.term,
    grade: form.value.grade,
  })
}
watchEffect(() => {
  if (form.value.classYear && form.value.term && form.value.grade) {
    getArrangeTemplateList()
  }
})
const onArrangeTemplateSelect = (event, index) => {
  console.log('onArrangeTemplateSelect: ', event, index)
  classList.value[index].arrangeTemplateName = event.name
}

// 时间段
const timeTemplateList = ref<any[]>([])
const getTimeTemplateList = async () => {
  timeTemplateList.value = await TimeTemplateApi.getList()
}
const onTimeTemplateSelect = (event, index) => {
  console.log('onTimeTemplateSelect: ', event, index)
  classList.value[index].timeTemplateName = event.name
}

const formRef = ref<FormInstance>()
const rules: FormInstance['rules'] = {
  classYear: [{ required: true, message: '请选择年份' }],
  term: [{ required: true, message: '请选择学期' }],
  subject: [{ required: true, message: '请选择科目' }],
  grade: [{ required: true, message: '请选择年级' }],
  planStudentCount: [{ required: true, message: '请输入计划招生人数' }],
  lessonChangeLimit: [{ required: true, message: '请选择调课次数限制' }],
  totalPrice: [{ required: true, message: '请输入总价' }],
  unitPrice: [{ required: true, message: '请输入单价' }],
  lessonHourFactor: [{ required: true, min: 0, message: '请输入课时业绩系数' }],
  salePerformanceFactor: [{ required: true, min: 0, message: '请输入销售业绩系数' }],
}

// 续报时间段
// const renewalTime = ref<Array<string>>([])
// watch(renewalTime, (val) => {
//   if (val) {
//     form.value.renewalStartTime = val[0]
//     form.value.renewalEndTime = val[1]
//   } else {
//     form.value.renewalStartTime = ''
//     form.value.renewalEndTime = ''
//   }
// })

// 导入前序班级学生
const importPrevStudent = ref(true)

// 提交保存
const createLoading = ref(false)
const onBatchCreate = async () => {
  createLoading.value = true
  let totalCount = 0
  let successCount = 0
  let errorCount = 0
  let skipCount = 0
  try {
    const isInvalid = await formRef.value?.validate()
    if (isInvalid) {
      return false
    }
    if (!classList.value || classList.value.length === 0) {
      return Message.error('没有班级信息')
    }
    for (const item of classList.value) {
      totalCount += 1

      if (!item.needCreate) {
        skipCount += 1
        continue
      }
      if (item.createStatus === 21) {
        skipCount += 1
        continue
      }
      if (!item.classroomId) {
        return Message.error('请指定教室')
      }
      if (!item.leadTeacherId) {
        return Message.error('请指定主讲老师')
      }
      if (!item.arrangeTemplateId) {
        return Message.error('请指定上课期段')
      }
      if (!item.timeTemplateId) {
        return Message.error('请指定上课时间段')
      }
      if (!item.classTypeId) {
        return Message.error('请指定班型')
      }
      if (!item.admissionYearLimit) {
        return Message.error('请指定入学年份限制')
      }
      try {
        item.createStatus = 1
        // 预排课
        const shecduleReq: ClassInfoApi.ClassScheduleReq = {
          leadTeacherId: item.leadTeacherId,
          campusId: item.campusId,
          classroomId: item.classroomId,
          arrangeTemplateId: item.arrangeTemplateId,
          timeTemplateId: item.timeTemplateId,
        }
        const classScheduleList = await ClassInfoApi.generateShecdule(shecduleReq) || []
        const conflictLesson = classScheduleList.find(lesson => lesson.conflictInfo != null)
        if (conflictLesson) {
          item.conflictInfo = conflictLesson.conflictInfo
          item.createStatus = 10
          errorCount += 1
          continue
        }
        // 创建
        const createReq: ClassInfoApi.ClassCreateReq = {
          ...unref(form),
          ...item,
          name: `${form.value.classYear}${useDictLabel('TermEnum', form.value.term)}${useDictLabel('Grade', form.value.grade)}${useDictLabel('Subject', form.value.subject)}${item.classTypeName}(${item.arrangeTemplateName}${item.timeTemplateName})`,
          importPrevStudent: importPrevStudent.value,
        }
        item.createStatus = 2
        await ClassInfoApi.createClass(createReq)
        item.createStatus = 21
        successCount += 1
      } catch (err) {
        console.warn('创建班级失败: ', err)
        item.createStatus = 20
        errorCount += 1
      }
    }

    Notification.info({
      title: '批量创建完成',
      content: `总计${totalCount}个班级，成功${successCount}个, 失败${errorCount}个, 跳过${skipCount}个!`,
    })
  } finally {
    createLoading.value = false
  }
}

onMounted(() => {
  getClassroomList()
  getLeadTeacherList()
  getAssistTeacherList()
  getClassTypeList()
  getTimeTemplateList()
})
</script>

<template>
  <ProPage>
    <template #title>
      <a-page-header title="批量创建班级" subtitle="针对长期班创建续报班级，支持自动导入前序班级学生" @back="router.back()" />
    </template>

    <a-space size="medium">
      <label class="label">前序班级筛选</label>
      <YearPicker v-model="classQuery.classYear" placeholder="年份" class="!w-150px" />
      <DictSelect v-model="classQuery.term" type="button" code="TermEnum" placeholder="学期" />
      <DictSelect v-model="classQuery.grade" type="select" code="Grade" placeholder="年级" class="!w-120px" />
      <DictSelect v-model="classQuery.subject" type="select" code="Subject" placeholder="科目" class="!w-120px" />
      <a-button type="primary" size="medium" @click="searchClass">
        批量生成
      </a-button>
    </a-space>
    <a-divider />
    <a-alert>
      下列信息将应用到每个班级上
    </a-alert>
    <a-spin :loading="classLoading" dot class="w-full">
      <a-form ref="formRef" :model="form" :rules="rules" auto-label-width>
        <a-card title="基础信息" class="section">
          <a-row :gutter="40">
            <a-col :span="8">
              <a-form-item label="年份" field="classTypeId">
                <a-year-picker v-model="form.classYear" placeholder="年份" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="学期" field="term">
                <DictSelect v-model="form.term" type="button" code="TermEnum" placeholder="学期" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="年级" field="grade">
                <DictSelect v-model="form.grade" type="select" code="Grade" placeholder="年级" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="科目" field="subject">
                <DictSelect v-model="form.subject" type="select" code="Subject" placeholder="科目" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="限制调课次数" field="lessonChangeLimit" tooltip="允许学生可调课次数，0代表不限次数">
                <a-input-number v-model="form.lessonChangeLimit" :min="0" placeholder="请输入限制调课次数">
                  <template #append>
                    次
                  </template>
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="上架状态" tooltip="下架状态将不会展示给家长端">
                <DictSelect v-model="form.saleStatus" type="button" code="SaleStatusEnum" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="课时业绩系数" field="lessonHourFactor" tooltip="用于计算老师业绩，一节课业绩=1*课时业绩系数">
                <a-input-number v-model="form.lessonHourFactor" mode="button" :step="0.1" :min="0" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="销售业绩系数" field="salePerformanceFactor" tooltip="用于计算课程顾问业绩，一次有效报名业绩=1*销售业绩系数">
                <a-input-number v-model="form.salePerformanceFactor" mode="button" :step="0.1" :min="0" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        <a-card id="enrollment" title="招生报名" class="section">
          <a-alert v-if="form.enrollStartTime && form.renewalStartTime && form.renewalEndTime" :show-icon="false" class="mb">
            <a-timeline direction="horizontal" mode="bottom" label-position="same">
              <a-timeline-item :label="form.renewalStartTime" dot-color="#52C419">
                续报期开始，允许前序学员提前报名调课，不允许转班
              </a-timeline-item>
              <a-timeline-item :label="form.renewalEndTime" dot-color="#F5222D">
                续报期结束，不允许报名，允许调课转班
              </a-timeline-item>
              <a-timeline-item :label="form.enrollStartTime">
                开放报名，允许所有人报名及调课转班
              </a-timeline-item>
            </a-timeline>
          </a-alert>
          <a-row :gutter="40">
            <a-col :span="12">
              <a-form-item label="续报期" tooltip="续报期开始后允许当前在读学员提前报名，续报期结束后不允许提前报名，但允许调课转班">
                <RangePicker
                  v-model:from="form.renewalStartTime" v-model:to="form.renewalEndTime" show-time format="YYYY-MM-DD HH:mm" :placeholder="['续报开始时间', '续报结束时间']" :time-picker-props="{
                    step: {
                      minute: 10,
                    },
                    defaultValue: ['13:30:00', '22:00:00'],
                  }"
                />
                <!-- <a-range-picker
                  v-model="renewalTime"
                  class="w-full"
                  show-time
                  :time-picker-props="{ defaultValue: ['12:00:00', '22:00:00'] }"
                  :placeholder="['续报开始时间', '续报结束时间']"
                /> -->
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="开放报名时间" tooltip="该时间后允许所有人报名">
                <a-date-picker
                  v-model="form.enrollStartTime"
                  class="w-full"
                  show-time
                  format="YYYY-MM-DD HH:mm"
                  :time-picker-props="{ step: { minute: 10 }, defaultValue: '09:00:00' }"
                  placeholder="开放报名时间"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="计划招生" field="planStudentCount">
                <a-input-number v-model="form.planStudentCount" :min="0" placeholder="请输入计划招生人数">
                  <template #prefix>
                    <icon-user />
                  </template>
                  <template #append>
                    人
                  </template>
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="单价" field="unitPrice">
                <a-input-number v-model="form.unitPrice" :min="0" placeholder="请输入单价" :hide-button="true">
                  <template #append>
                    元
                  </template>
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="总价" field="totalPrice">
                <a-input-number v-model="form.totalPrice" :min="0" placeholder="请输入总价" :hide-button="true">
                  <template #append>
                    元
                  </template>
                </a-input-number>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        <a-card title="班级列表" class="section" :extra="`共${classList.length}个班`">
          <a-empty v-if="!classList || classList.length === 0 " />
          <a-table
            v-else
            size="small"
            :columns="columns"
            :scroll="{ x: '100%', y: '100%', minWidth: 960 }"
            column-resizable
            :data="classList"
            :pagination="false"
            :loading="classLoading"
          >
            <template #name="{ record, rowIndex }">
              <!-- <a-input v-model="record.name" :size="formSize" /> -->
              <div>
                {{ `${form.classYear}${useDictLabel('TermEnum', form.term)}${useDictLabel('Grade', form.grade)}${useDictLabel('Subject', form.subject)}${record.classTypeName}(${record.arrangeTemplateName}${record.timeTemplateName})` }}
              </div>
              <a-space>
                <a-tag size="small">
                  前序
                </a-tag>
                <span class="text-12px text-gray-4">{{ record.prevClassName }}</span>
                <span class="text-12px text-gray-4">{{ record.prevClassLeadTeacherName }}</span>
              </a-space>
            </template>
            <template #classroomId="{ record, rowIndex }">
              <ClassroomCascader v-model:campus-id="record.campusId" v-model:classroom-id="record.classroomId" :size="formSize" :options="classroomList" placeholder="请选择教室" />
              <!-- <ClassroomSelect v-model="record.classroomId" :size="formSize" placeholder="教室" :options="classroomList" @select="onClassroomSelect($event, rowIndex)" /> -->
            </template>
            <template #leadTeacherId="{ record, rowIndex }">
              <EmployeeSelect v-model="record.leadTeacherId" :size="formSize" type="LEAD_TEACHER" placeholder="主讲老师" :options="leadTeacherList" />
            </template>
            <template #assistTeacherId="{ record, rowIndex }">
              <EmployeeSelect v-model="record.assistTeacherId" :size="formSize" type="ASSIST_TEACHER" placeholder="辅导老师" :options="assistTeacherList" />
            </template>
            <template #classTypeId="{ record, rowIndex }">
              <ClassTypeSelect v-model="record.classTypeId" :size="formSize" :options="classTypeList" @select="onClassTypeSelect($event, rowIndex)" />
            </template>
            <template #admissionYearLimit="{ record, rowIndex }">
              <a-year-picker v-model="record.admissionYearLimit" :size="formSize" placeholder="入学年份限制" />
            </template>
            <template #enrollPermission="{ record, rowIndex }">
              <span v-if="record.classTypeId && record.admissionYearLimit">允许<span class="font-600">{{ calculateGradeLimitLegacy(record.admissionYearLimit) }}</span>且拥有<span class="font-600">{{ record.classTypeName }}及以上权限</span>的学生报名</span>
              <span v-else>-</span>
            </template>

            <template #arrangeTemplateId="{ record, rowIndex }">
              <ArrangeTemplateSelect v-model="record.arrangeTemplateId" :size="formSize" :options="arrangeTemplateList" @select="onArrangeTemplateSelect($event, rowIndex)" />
            </template>
            <template #timeTemplateId="{ record, rowIndex }">
              <TimeTemplateSelect v-model="record.timeTemplateId" :size="formSize" :options="timeTemplateList" @select="onTimeTemplateSelect($event, rowIndex)" />
            </template>
            <template #status="{ record, rowIndex }">
              <a-space v-if="!record.createStatus" size="mini">
                <a-checkbox v-model="record.needCreate">
                  是否创建
                </a-checkbox>
              </a-space>
              <a-space v-if="record.createStatus === 1">
                <icon-refresh :style="{ color: '#165dff' }" spin />
                冲突检测...
              </a-space>
              <a-space v-if="record.createStatus === 10">
                <a-popover title="排课冲突">
                  <a-tag color="red" class="cursor-pointer!">
                    <template #icon>
                      <icon-exclamation-circle-fill />
                    </template>
                    排课冲突
                  </a-tag>
                  <template #content>
                    <ConflictTip :data="record.conflictInfo" />
                  </template>
                </a-popover>
              </a-space>
              <a-space v-if="record.createStatus === 2">
                <icon-refresh :style="{ color: '#165dff' }" spin />
                创建中...
              </a-space>
              <a-space v-if="record.createStatus === 21">
                <icon-check-circle :style="{ color: '#00b42a' }" />
                创建成功
              </a-space>
              <a-space v-if="record.createStatus === 20">
                <icon-close-circle :style="{ color: '#f53f3f' }" />
                创建失败
              </a-space>
            </template>
          </a-table>
        </a-card>
        <div class="w-full flex-row-end-center">
          <a-space>
            <a-checkbox v-model="importPrevStudent" :disabled="createLoading">
              导入前序班级学生
            </a-checkbox>
            <a-button v-permission="['edu:class:write']" type="primary" :disabled="!classList || classList.length === 0" :loading="createLoading" @click="onBatchCreate">
              <template #icon>
                <icon-save />
              </template>
              开始创建
            </a-button>
          </a-space>
        </div>
      </a-form>
    </a-spin>
  </ProPage>
</template>

<style lang="less" scoped>
:deep(.arco-card-header) {
  position: sticky;
  top: 0;
  z-index: 2;
  background: #fff;
  padding: 10px 0;
}

:deep(.section .arco-card-header) {
  position: relative;
  z-index: 1;
}
</style>
